/*
 * @Author: 聆风 522361856@qq.com
 * @Date: 2025-08-14 17:11:34
 * @LastEditors: 聆风 522361856@qq.com
 * @LastEditTime: 2025-08-14 19:32:29
 * @FilePath: \vue3-source-code-analysis\scripts\dev.js
 * @Description:
 *
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved.
 */
//打包文件命令，打包成js
import minimist from "minimist";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";
import { createRequire } from "module";
import esbuild from "esbuild";
//获取命令行参数
const args = minimist(process.argv.slice(2));

//esm使用cjs变量
const __filename = fileURLToPath(import.meta.url); //获取文件的绝对路径 file: ->/usr
const __dirname = dirname(__filename); //当前文件的目录路径
const require = createRequire(import.meta.url);
const target = args._[0]; //目标项目
const format = args.f || "iife"; //模块化规范
console.log(__filename, __dirname);

//根据路径获取项目入口文件
const entry = resolve(__dirname, `../packages/${target}/src/index.ts`);
const pkg = require(`../packages/${target}/package.json`);

//根据需要打包
esbuild
  .context({
    entryPoints: [entry], //入口
    outfile: resolve(__dirname, `../packages/${target}/dist/${target}.js`), //出口
    bundle: true, //依赖打包到一起
    platform: "browser", //产物给浏览器使用
    sourcemap: true, //源代码，调试用的
    format, //cjs,esm,iife
    globalName: pkg.buildOptions?.name, //iife需要名字
  })
  .then((ctx) => {
    console.log("start dev");
    return ctx.watch(); //监控入口文件持续打包
  });
